import 'package:flutter_ebook/http/dio_instance.dart';
import 'package:flutter_ebook/http/spider/api_string.dart';
import 'package:flutter_ebook/model/activity.dart';
import 'package:html/dom.dart';
import 'package:html/parser.dart';

class SpiderApi {
  static SpiderApi? _instance; //单例模式

  SpiderApi._(); //私有构造函数
  static SpiderApi instance() {
    return _instance ??= SpiderApi._(); //单例模式
  }

  Future<List<Activity>> fetchHomeData() async {
    // 实现爬虫逻辑
    String htmlStr = await DioInstance.instance()
        .getString(path: ApiString.BASE_URL); //返回爬虫数据

    Document doc = parse(htmlStr); // 解析数据
    List<Activity> activities = []; //定义活动列表
    List<Element> elements =
        doc.querySelectorAll(".books-activities .book-activity"); //解析数据并返回
    // print("elements: $elements");
    for (var element in elements) {
      String url = element.attributes["href"]?.trim() ?? ""; //获取链接
      String cover =
          ApiString.getBookActivityCover(element.attributes["style"]); //获取封面
      String title =
          element.querySelector(".book-activity-title")?.text.trim() ??
              ""; //获取标题
      String label =
          element.querySelector(".book-activity-label")?.text.trim() ??
              ""; //获取标签
      String time =
          element.querySelector(".book-activity-time time")?.text.trim() ??
              ""; //获取时间
      activities.add(Activity(
          url: url,
          cover: cover,
          title: title,
          label: label,
          time: time)); //添加到列表中
    }
    // print("activities: $activities"); //打印数据
    return activities; //返回数据
  }
}
